import { upload, useRequest } from "../../../../utils/request";

const WeValidator = require('../../../../package/we-validator.min')

Component({
    properties: {},
    data: {
        fileList: [],
        textLength: 0,
    },
    methods: {
        onLoad(options) {
            this.setData({
                orderNo: options.id
            })
            this.request = new useRequest('api/usertalkorder', { hold: true }, this)

            this.validatorInstance = new WeValidator({
                rules: {
                    description: {
                        required: true,
                    },
                },
                messages: {
                    description: {
                        required: '请输入内容',
                    },
                },
            })
        },
        textInput(e) {
            const cursor = e.detail.cursor
            this.setData({
                textLength: cursor > 200 ? 200 : cursor
            })
        },
        chooseImage(e) {
            const { file } = e.detail;
            wx.showLoading({
                title: '正在上传中',
                mask: true
            })
            Promise.allSettled(file.map(item => {
                return upload(item.url)
            })).then(url => {
                wx.hideLoading()
                this.setData({
                    fileList: [...this.data.fileList, ...url.map(item => {
                        return { url: item.value }
                    })]
                })
            })
        },
        removeImage(e) {
            const { index } = e.detail
            let data = this.data.fileList
            data.splice(index, 1)
            this.setData({
                fileList: data
            })
        },
        submit(e) {
            const value = e.detail.value

            if (this.validatorInstance.checkData(value)) {
                this.request.run({
                    ...value,
                    order_no: this.data.orderNo,
                    imgs: this.data.fileList.map(item => item.url)
                }).then(() => {
                    wx.showToast({
                        title: '发布成功',
                    })
                    setTimeout(() => {
                        wx.navigateBack()
                    }, 1500)
                })
            }
        }
    }
});
